package com.neu.servlet.wty;

import com.neu.service.wty.UserService;
import com.neu.util.EmailUtil;
import org.json.JSONException;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "sendEmailServlet", urlPatterns = {"/sendEmailServlet.do"})
public class sendEmailServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("准备判断邮箱");
        String u_mail=request.getParameter("u_mail");
        System.out.println(u_mail);
        UserService userService=new UserService();
        if (u_mail.isEmpty()){
            System.out.println("输入为空!");
            PrintWriter out = response.getWriter();
            JSONObject data = new JSONObject();
            try {
                data.put("status", "isNull");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            out.println(data.toString());
        }else {
            boolean flag=userService.findByEmail(u_mail);
            if (flag){
                EmailUtil.sendEmail(u_mail);
                System.out.println("发送邮件成功");
                //验证成功
                PrintWriter out = response.getWriter();
                JSONObject data = new JSONObject();
                try {
                    data.put("status", "success");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                out.println(data.toString());
            }
            else{
                System.out.println("邮箱输入错误");
                // 验证失败
                JSONObject data = new JSONObject();
                try {
                    data.put("status", "fail");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                PrintWriter out = response.getWriter();
                out.println(data.toString());
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}